<template>
  <div class="collections-container">
    <!-- 标题和新增按钮 -->
    <div class="page-header">
      <h2>藏品管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增藏品
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="藏品名称">
          <el-input v-model="searchForm.name" placeholder="请输入藏品名称" clearable />
        </el-form-item>
        <el-form-item label="藏品分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格卡片 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="藏品名称" />
        <el-table-column label="藏品分类" align="center">
          <template #default="{ row }">
            {{ getCategoryName(row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column prop="period" label="年代" />
        <el-table-column prop="location" label="展厅位置" />
        <el-table-column label="藏品图片" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.imageUrl"
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              class="table-image"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="是否精选" align="center">
          <template #default="{ row }">
            <el-tag :type="row.featured === 1 ? 'success' : 'info'">
              {{ row.featured === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增藏品' : '编辑藏品'"
      v-model="dialogVisible"
      width="650px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="藏品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入藏品名称" />
        </el-form-item>

        <el-form-item label="藏品分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择藏品分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="年代" prop="period">
          <el-input v-model="formData.period" placeholder="请输入藏品年代" />
        </el-form-item>

        <el-form-item label="藏品图片" prop="imageUrl">
          <el-upload
            class="exhibit-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="customUpload"
          >
            <img v-if="formData.imageUrl" :src="formData.imageUrl" class="exhibit-image" />
            <el-icon v-else class="exhibit-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            支持 jpg/png 文件，且不超过 2MB
          </div>
        </el-form-item>

        <el-form-item label="是否精选" prop="featured">
          <el-radio-group v-model="formData.featured">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="展厅位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入展厅位置" />
        </el-form-item>

        <el-form-item label="藏品描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入藏品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCollectionsPage, removeCollections, addCollections, updateCollections } from '@/api/collections'
import { getCategoryList } from '@/api/category'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])

// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 搜索表单
const searchForm = ref({
  name: '',
  categoryId: ''
})

// 修改分类选项为空数组，等待API获取
const categories = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitLoading = ref(false)

// 表单数据
const formData = ref({
  id: '',
  name: '',
  categoryId: '',
  period: '',
  imageUrl: '',
  featured: 0,
  location: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入藏品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择藏品分类', trigger: 'change' }
  ],
  period: [
    { required: true, message: '请输入藏品年代', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入展厅位置', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入藏品描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 获取藏品列表
const fetchCollections = async () => {
  loading.value = true
  try {
    const params = {
      current: page.value.current,
      size: page.value.size,
      name: searchForm.value.name,
      categoryId: searchForm.value.categoryId
    }
    const res = await getCollectionsPage(params)
    tableData.value = res.records
    page.value.total = res.total
  } catch (error) {
    ElMessage.error('获取藏品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value.current = 1
  fetchCollections()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    name: '',
    categoryId: ''
  }
  handleSearch()
}

// 添加获取分类列表的方法
const fetchCategories = async () => {
  try {
    const res = await getCategoryList()
    // 假设返回的分类数据格式为 {id, name}，转换为选项格式
    categories.value = res.map(item => ({
      value: item.id,
      label: item.name
    }))
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  }
}

// 修改handleAdd方法，确保分类数据已加载
const handleAdd = async () => {
  if (categories.value.length === 0) {
    await fetchCategories()
  }
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 修改handleEdit方法，确保分类数据已加载
const handleEdit = async (row) => {
  if (categories.value.length === 0) {
    await fetchCategories()
  }
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该藏品吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await removeCollections(row.id)
      ElMessage.success('删除成功')
      fetchCollections()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  page.value.size = val
  fetchCollections()
}

// 当前页改变
const handleCurrentChange = (val) => {
  page.value.current = val
  fetchCollections()
}

// 图片上传前的验证
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const customUpload = async (options) => {
  try {
    // 这里实现文件上传逻辑
    const reader = new FileReader()
    reader.readAsDataURL(options.file)
    reader.onload = (e) => {
      formData.value.imageUrl = e.target.result
    }
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          await addCollections(formData.value)
          ElMessage.success('添加成功')
        } else {
          await updateCollections(formData.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchCollections()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  formData.value = {
    id: '',
    name: '',
    categoryId: '',
    period: '',
    imageUrl: '',
    featured: 0,
    location: '',
    description: ''
  }
}

// 添加获取分类名称的方法
const getCategoryName = (categoryId) => {
  const category = categories.value.find(item => item.value === categoryId)
  return category ? category.label : '未知分类'
}

// 修改onMounted，添加获取分类列表
onMounted(() => {
  fetchCategories()  // 获取分类列表
  fetchCollections()
})
</script>

<style scoped>
.collections-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.el-card {
  margin-bottom: 20px;
}

.table-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 调整表单项间距 */
.el-form--inline .el-form-item {
  margin-right: 20px;
}

/* 调整搜索框宽度 */
.el-input,
.el-select {
  width: 200px;
}

/* 添加新的样式 */
.dialog-form {
  max-width: 600px;
  margin: 0 auto;
}

.exhibit-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.exhibit-uploader:hover {
  border-color: #409EFF;
}

.exhibit-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.exhibit-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}
</style> 